/*
 * Copyright 2010 Christoph Widulle (christoph.widulle@googlemail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
 * License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */



package com.android1.amarena2d.engine;

import com.android1.amarena2d.actions.base.Action;
import com.android1.amarena2d.commons.collections.FixedSizeStagingList;
import com.android1.amarena2d.nodes.behavior.ActionTarget;

public class TargetActionsStore extends EngineObject {

    final FixedSizeStagingList<Action> actions;
    final ActionTarget target;
    boolean paused;


    public TargetActionsStore(ActionTarget target, boolean paused, int actionsSize) {
        this.target = target;
        this.paused = paused;
        this.actions = new FixedSizeStagingList<Action>(actionsSize);
    }

    public void run(Action action) {
        if (action.isRunning())
            stop(action);
        action.start(target);
        actions.add(action);
    }

    public void stop(Action action) {
        if (action.isRunning()) {
            action.stop();
            action.complete(target);
            actions.remove(action);
        } else {
            if (AmarenaEngine.DEBUG)
                engine.log("TargetActionsStore", "Ignoring to stop Action which is not running. " + action.toString());
        }
    }

    public void stopAll() {
        actions.applyChanges();
        int s = actions.getCount();
        for (int i = 0; i < s; i++) {
            Action a = actions.get(i);
            a.stop();
            a.complete(target);
        }
        actions.clear();

    }

    public boolean isTargetActive() {
        return target.isActive();
    }

    public void pause() {
        paused = true;
    }

    public void resume() {
        paused = false;
    }

    public TargetActionsStore(ActionTarget target) {
        this(target, false, engine.getConfig().get(Config.ACTIONS_MAX_CONCURRENT_BY_TARGET));
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        TargetActionsStore that = (TargetActionsStore) o;

        if (!target.equals(that.target)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return target.hashCode();
    }
}
